<?php

namespace app\controllers;

use Yii;
use yii\web\Response;
use app\components\BaseController;
use app\components\Api;
use app\components\Loyalty;
use app\components\Log;
use app\models\Tenant;
use yii\helpers\ArrayHelper;
use yii\web\ServerErrorHttpException;

class SmsController extends BaseController
{

    public function actionIndex()
    {
    }

    /**
     * 第三方授权处理
     * 请在设置OAuth链接的时候把要跳转的链接设置为state参数，把要跳转的方法设置为method参数
     * 请参考上面MenuSet()方法中设置$center_url的方式
     */
    public function actionOauth()
    {
    	Log::debug('SMS OAUTH GET FIELDS', $_GET);
    
    	// 删除session
    	$session = Yii::$app->session;
    	$session->destroy();
    	    
    	if (empty($_GET['appid'])) {
    		throw new ServerErrorHttpException('appid not found');
    	}
    	
    	// 重要！获取appid，作为全局支持
    	$this->setAppid($_GET['appid']);
    
    	// 设置identifier
    	$tenant = Tenant::find()->where(['appid' => $_GET['appid']])->one();
    
    	if (empty($tenant->identifier)) {
    		throw new ServerErrorHttpException('identifier not found');
    	}
    	$this->setIdentifier($tenant->identifier);
    
    	// 设置loyalty config
    	if (empty($tenant->tenant_id) || empty($tenant->loyalty_accountid) || empty($tenant->loyalty_username) || empty($tenant->loyalty_password)) {
    		throw new ServerErrorHttpException('loyalty config not found');
    	} else {
    		$session = Yii::$app->session;
    		$loyaltyConfig = [
	    		'tenant_id' => $tenant->tenant_id,
	    		'app_id' => $tenant->appid,
	    		'loyalty_accountid' => $tenant->loyalty_accountid,
	    		'loyalty_username' => $tenant->loyalty_username,
	    		'loyalty_password' => $tenant->loyalty_password,
	    		'loyalty_url' => $tenant->loyalty_url,
    		];
    		$session->set('loyaltyConfig', $loyaltyConfig);
    	}
    
    	// 重要！获取code，作为全局支持
    	if (empty($_GET['code'])) {
    		throw new ServerErrorHttpException('code not found');
    	}
    	
    	// 重要方法！把该用户的微信信息和Loyalty信息存到session中
    	if (!empty($_GET['mobile'])) {
    		$this->setMobile($_GET['mobile']);
//     		$exists = $this->checkExists($_GET['code'], $_GET['mobile']);
//     		if (!$exists) {
//     			throw new ServerErrorHttpException('mobile and code do not match.');
//     		}
    	} else {
    		$this->setCode($_GET['code']);
    	}
    
    	// 使用获取的method参数跳转到对应的业务层
    	if (empty($_GET['method'])) {
    		throw new ServerErrorHttpException('method not found');
    	}
    	$method = str_replace('_', '/', $_GET['method']);
    
//     	Log::debug('SMS OAUTH SUCCESS');
    	
    	if (isset($_GET['id'])) {
    		return $this->redirect([$method, 'id' => $_GET['id']]);
    	} else {
    		if (isset($_GET['redirect_url'])) {
    			return $this->redirect([$method, 'oauth' => 'sms', 'redirect_url' => $_GET['redirect_url'], 'redirect_name' => $_GET['redirect_name']]);
    		} else {
    			return $this->redirect([$method, 'oauth' => 'sms']);
    		}
    	}
    }
}
